﻿using System;
using System.IO;

namespace Terraria.ModLoader.IO
{
	// Token: 0x020002C0 RID: 704
	public static class BinaryIO
	{
		// Token: 0x06001BA5 RID: 7077 RVA: 0x00013E70 File Offset: 0x00012070
		public static void WriteItem(this BinaryWriter writer, Item item, bool readStack = false, bool readFavorite = false)
		{
			ItemIO.Send(item, writer, readStack, readFavorite);
		}

		// Token: 0x06001BA6 RID: 7078 RVA: 0x00013E7B File Offset: 0x0001207B
		public static Item ReadItem(this BinaryReader reader, bool readStack = false, bool readFavorite = false)
		{
			return ItemIO.Receive(reader, readStack, readFavorite);
		}

		// Token: 0x06001BA7 RID: 7079 RVA: 0x004313F8 File Offset: 0x0042F5F8
		public static void WriteVarInt(this BinaryWriter writer, int value)
		{
			uint num;
			for (num = (uint)value; num >= 128u; num >>= 7)
			{
				writer.Write((byte)(num | 128u));
			}
			writer.Write((byte)num);
		}

		// Token: 0x06001BA8 RID: 7080 RVA: 0x0043142C File Offset: 0x0042F62C
		public static int ReadVarInt(this BinaryReader reader)
		{
			int num = 0;
			int num2 = 0;
			while (num2 != 35)
			{
				byte b = reader.ReadByte();
				num |= (int)(b & 127) << num2;
				num2 += 7;
				if ((b & 128) == 0)
				{
					return num;
				}
			}
			throw new FormatException("variable length int with more than 32 bits");
		}

		// Token: 0x06001BA9 RID: 7081 RVA: 0x00431470 File Offset: 0x0042F670
		public static void SafeWrite(this BinaryWriter writer, Action<BinaryWriter> write)
		{
			MemoryStream memoryStream = new MemoryStream();
			write(new BinaryWriter(memoryStream));
			writer.WriteVarInt((int)memoryStream.Length);
			memoryStream.Position = 0L;
			memoryStream.CopyTo(writer.BaseStream);
		}

		// Token: 0x06001BAA RID: 7082 RVA: 0x004314B0 File Offset: 0x0042F6B0
		public static void SafeRead(this BinaryReader reader, Action<BinaryReader> read)
		{
			int num = reader.ReadVarInt();
			MemoryStream memoryStream = new MemoryStream(reader.ReadBytes(num));
			read(new BinaryReader(memoryStream));
			if (memoryStream.Position != (long)num)
			{
				throw new IOException(string.Concat(new object[]
				{
					"Read underflow ",
					memoryStream.Position,
					" of ",
					num,
					" bytes"
				}));
			}
		}
	}
}
